import Taro, { Component } from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import classNames from 'classnames'
import { DNavBar, DAgree, DImagesupload, DSelectMap, DAtInpute } from '@/components'
import { AtForm, AtButton, AtActionSheet } from 'taro-ui'
import http from '@/api'
import sdk from "@/common/sdk"
import './enterpriseform.scss'

const peopleRight = require('../assets/people_right.png')
const peopleLeft = require('../assets/people_info.png')
export default class Enterpriseform extends Component {

    constructor(props) {
        super(props)
        this.state = {
            title: '企业认证',
            enterprisefrom: {},
            status: true,
            list: [],
            itemlist: [],
            firstList: [],
            secondList: [],
            fileList: [],
            success: 0, // 0:唔提交 1:已提交 请耐心等待，平台管理员将会在3个工作日内审核您的申请  2:不通过
            successText: '您的企业认证审核未通过，请修改后重新提交申请',
            isOpened: false,
            entId: '',
            img1: [],
            img2: [],
            img3: [],
            img4: [],
            showimg: true,
            typeList: [
                {
                    text: '4S店',
                    status: true
                },
                {
                    text: '经销商',
                    status: false
                }
            ],
            approEnt: '', // 修改营业执照是否审核中  3 审核中
        }
    }
    componentWillMount() {
        let { entId, entName, edit, rep } = this.$router.params
        let { enterprisefrom } = this.state
        if (entName) {
            enterprisefrom.name = decodeURIComponent(entName)
            this.setState({
                enterprisefrom
            })
            return
        }
        if (rep) {
            // 获取企业信息填充页面
            this.getEntinfo()
            return
        }
        if (edit) { // 修改营业执照
            this.setState({
                title: '修改营业执照'
            })
            // 获取企业信息填充页面
            this.getEntinfo(edit)
            return
        }
        if (entId) {
            this.getEntinfo(entId)
            this.setState({
                success: 1,
                entId,
                showimg: false
            })

        }
    }

    componentDidShow() {
        sdk.setTitleInfo('企业认证')
    }

    getEntinfo(id = '') {
        let { enterprisefrom } = this.state
        http.getEntinfo({ id }).then(res => {
            if (!res) {
                return
            }
            this.setState({
                showimg: false
            })
            // console.log(res)
            let { img1, img2, img3, img4 } = this.state
            res.fileList.map(item => {
                if (item.cfType === '1') {
                    img1.push({
                        id: item.cfFileId,
                        url: item.cfFileUrl
                    })
                } else if (item.cfType === '2') {
                    img2.push({
                        id: item.cfFileId,
                        url: item.cfFileUrl
                    })
                } else if (item.cfType === '3') {
                    img3.push({
                        id: item.cfFileId,
                        url: item.cfFileUrl
                    })
                } else if (item.cfType === '4') {
                    img4.push({
                        id: item.cfFileId,
                        url: item.cfFileUrl
                    })
                }
            })
            // console.log(img1, img2, img3, img4)
            this.onChangeImages(img1)
            this.onChangeImage(img4)
            this.onChangeFirst(img2)
            this.onChangeSecond(img3)
            this.setState({
                enterprisefrom: {
                    ...enterprisefrom,
                    name: res.entName,
                    account: res.entCreditCode,
                    people: res.entOwner,
                    region: res.entDis,
                    itemregion: res.entAddr,
                    type: res.entAtt,
                    id: res.id
                },
                img1,
                img2,
                img3,
                img4,
                showimg: true,
                approEnt: res.approEnt
            })
        })
    }
    onChangeImages(list) {
        let { fileList } = this.state
        let listobj = []
        list.map(item => {
            listobj.push({
                "cfFileId": `${item.id}`,
                "cfFileName": '',
                "cfType": 1,
                "cfFileUrl": `${item.url}`
            })
        })
        this.setState({
            // fileList: [...fileList, listobj],
            listobj,
            list
        })
    }

    onChangeImage(itemlist) {
        let { fileList } = this.state

        let itemlistobj = []
        itemlist.map(item => {
            itemlistobj.push({
                "cfFileId": `${item.id}`,
                "cfFileName": '',
                "cfType": 4,
                "cfFileUrl": `${item.url}`
            })
        })
        this.setState({
            // fileList: [...fileList, itemlistobj],
            itemlistobj,
            itemlist
        })
    }

    onChangeFirst(firstList) {
        let { fileList } = this.state
        let firstListobj = []
        firstList.map(item => {
            firstListobj.push({
                "cfFileId": `${item.id}`,
                "cfFileName": '',
                "cfType": 2,
                "cfFileUrl": `${item.url}`
            })
        })
        this.setState({
            // fileList: [...fileList, firstListobj],
            firstListobj,
            firstList
        })
    }

    onChangeSecond(secondList) {
        let { fileList } = this.state
        let secondListobj = []
        secondList.map(item => {
            secondListobj.push({
                "cfFileId": `${item.id}`,
                "cfFileName": '',
                "cfType": 3,
                "cfFileUrl": `${item.url}`
            })
        })
        this.setState({
            // fileList: [...fileList, secondListobj],
            secondListobj,
            secondList
        })
    }

    onHandleImage = (status = '') => {
        if (status !== 0) {
            return
        }
        let imgkey = ''
        if (status === 0) {
            imgkey = 'enterprise'
        }
        Taro.navigateTo({
            url: `/pages/itemImages/itemImages?status=${imgkey}`
        })
    }
    // 地区选择
    onChangeHandle(value) {
        let { enterprisefrom } = this.state
        enterprisefrom.region = ''
        Object.values(value).forEach(item => {
            enterprisefrom.region += item
        })
        this.setState({
            enterprisefrom
        })
    }

    getEnterForm(key, value) {
        if (key) {
            this.setState({
                enterprisefrom: Object.assign(this.state.enterprisefrom, { [key]: value })
            })
        }
    }

    handleChangeName(name) {
        this.getEnterForm('name', name)
    }
    handleChangeAccount(account) {
        this.getEnterForm('account', account)
    }
    handleChangePeople(people) {
        this.getEnterForm('people', people)
    }
    handleChangeItemregion(itemregion) {
        this.getEnterForm('itemregion', itemregion)
    }
    onHandleChange(status) {
        this.setState({
            status
        })
    }

    onCancelHandle() {
        this.setState({
            isOpened: false
        })
    }

    onSubmitHandle() {
        let { enterprisefrom, typeList } = this.state
        typeList.forEach(item => {
            if (item.status) {
                enterprisefrom.type = item.text
            }
        })
        this.setState({
            isOpened: false,
            enterprisefrom
        })
    }

    onHandleType() {
        let { isOpened } = this.state
        isOpened = !isOpened
        this.setState({
            isOpened
        })
    }

    // 企业性质选择
    onActive(active) {
        let { typeList, enterprisefrom } = this.state
        typeList.forEach((item, i) => {
            item.status = false
            if (i === active) {
                item.status = true
                enterprisefrom.type = item.text
            }
        })

        this.setState({
            typeList,
            enterprisefrom,
            isOpened: false,
        })

    }

    tipShowTaost(title) {
        return Taro.showToast({
            title,
            icon: 'none',
            duration: 800
        })
    }

    onSubmit() {
        let { enterprisefrom, list, firstList, itemlist, secondList, listobj, itemlistobj, firstListobj, secondListobj, status, entId, approEnt } = this.state
        let _objkey = ['name', 'account', 'people', 'region', 'itemregion', 'type',]
        let _status = false, _item = ''
        const _objText = {
            name: '请输入营业执照上的企业名称',
            account: '请输入企业社会信用代码',
            people: '请输入企业法人名字',
            region: '请选择企业所在城市',
            itemregion: '请输入企业地址',
            type: '请选择企业性质'
        }
        // _objkey.map(item => {
        //     if (!enterprisefrom[item]) {
        //         _status = true
        //     }
        // })
        for (let i = 0, j = _objkey.length; i < j; i++) {
            if (!enterprisefrom[_objkey[i]]) {
                _status = true
                _item = _objkey[i]
                break
            }
        }

        // console.log(_item)
        let rules = /^[a-zA-Z\d]{18}/

        if (_status) {
            return this.tipShowTaost(_objText[_item])
        }
        else if (enterprisefrom.name.length < 4) {
            return this.tipShowTaost('请输入企业名称大于4个字！')
        }
        else if (enterprisefrom.name.length > 50) {
            return this.tipShowTaost('请输入企业名称小于50个字！')
        }
        else if (enterprisefrom.account.length !== 18) {
            return this.tipShowTaost('请输入18位的企业信用代码')
        } else if (!rules.test(enterprisefrom.account)) {
            return this.tipShowTaost('社会信用代码只能包括字母或数字')
        } else if (list.length === 0) {
            return this.tipShowTaost('请上传企业营业执照照片！')
        } else if (itemlist.length === 0) {
            return this.tipShowTaost('请上传企业门店照片！')
        } else if (firstList.length === 0) {
            return this.tipShowTaost('请上传身份证正面照片！')
        } else if (secondList.length === 0) {
            return this.tipShowTaost('请上传身份证背面照片！')
        } else if (!status) {
            return this.tipShowTaost('请阅读并同意《企业认证协议》')
        }
        let fileList = [...listobj, ...itemlistobj, ...firstListobj, ...secondListobj]
        // 去重
        let result = {} // 利用对象键名不能重复进行去重
        for (let i = 0, l = fileList.length; i < l; i++) {
            result[fileList[i].cfFileId] = fileList[i]
        }
        let newArr = []
        Object.keys(result).forEach(item => {
            newArr.push(result[item])
        })

        let _obj = {
            entAddr: enterprisefrom.itemregion,
            entAtt: enterprisefrom.type,
            entCreditCode: enterprisefrom.account,
            entDis: enterprisefrom.region,
            entName: enterprisefrom.name,
            entOwner: enterprisefrom.people,
            entLicenseUrl: listobj[0].cfFileUrl,
            fileList: newArr
        }

        if (entId) {
            _obj = {
                ..._obj,
                id: entId
            }
        }
        if (this.$router.params.edit) {
            // 修改营业执照
            _obj = {
                ..._obj,
                id: enterprisefrom.id
            }

            if (approEnt == 3) {
                this.tipShowTaost("您已提交过申请！待平台运营人员审核，请耐心等待。")
                return
            }
            http.updateEntBusinessLicense(_obj).then(res => {
                Taro.showToast({
                    title: '已提交修改!',
                    duration: 800,
                    mask: true
                }).then(() => {
                    setTimeout(() => {
                        Taro.navigateBack({
                            delta: 1
                        })
                    }, 1000);
                })
            })
            return
        }

        if (this.$router.params.rep) {
            // 重新认证
            _obj = {
                ..._obj,
                id: enterprisefrom.id
            }
        }
        http.ApproEntryprise(_obj).then(data => {
            // Taro.navigateTo({
            //     url: "/pages/enterprisedetail/enterprisedetail"
            // })
            Taro.showToast({
                title: '已提交企业认证!',
                duration: 800,
                mask: true
            }).then(() => {
                setTimeout(() => {
                    Taro.redirectTo({
                        url: '/pages/myinfo/authentication'
                    })
                }, 1000);
            })
        })
    }

    handleSubmitText() {
        const { entId, edit } = this.$router.params
        if (entId) {
            return '重新提交'
        }
        if (edit) {
            return '提交修改'
        }
        return '提交登记'
    }

    render() {
        const {
            title,
            success,
            successText,
            enterprisefrom,
            isOpened,
            typeList,
            entId,
            status,
            img1,
            img2,
            img3,
            img4,
            showimg
        } = this.state
        let { rep, edit } = this.$router.params
        const itemImagesHtml = (status = 0) => {
            return <View className='b_enterpriseform__images_enterpris'>
                <View className='item_title'>
                    <Text className='item_title__left'>{status === 0 ? '企业营业执照' : '企业门店照片'}</Text>
                    {
                        status === 0 && <Text className='item_title__right' onClick={this.onHandleImage.bind(this, status)}>查看范例</Text>
                    }
                </View>
                {
                    (rep || edit) ? (img1.length != 0 && <DImagesupload value={status === 0 ? img1 : img4} count={1} onChangeImages={status === 0 ? this.onChangeImages.bind(this) : this.onChangeImage.bind(this)}></DImagesupload>)
                        : <DImagesupload value={status === 0 ? img1 : img4} count={1} onChangeImages={status === 0 ? this.onChangeImages.bind(this) : this.onChangeImage.bind(this)}></DImagesupload>
                }
            </View>
        }
        const itemPeople =
            <View className='b_enterpriseform__images_enterpris'>
                <View className='item_title'>
                    <Text className='item_title__left'>法人身份证</Text>
                </View>

                <View className='b_enterpriseform__people'>
                    {
                        (rep || edit) ? (img2.length && <DImagesupload value={img2} onChangeImages={this.onChangeFirst.bind(this)} text={'上传人像面'} count={1} bgImage={peopleRight}></DImagesupload>)
                            : <DImagesupload value={img2} onChangeImages={this.onChangeFirst.bind(this)} text={'上传人像面'} count={1} bgImage={peopleRight}></DImagesupload>
                    }
                    {
                        (rep || edit) ? (img3.length && <DImagesupload value={img3} onChangeImages={this.onChangeSecond.bind(this)} text={'上传国徽面'} className="b_enterpriseform__people_item" count={1} bgImage={peopleLeft}></DImagesupload>)
                            : <DImagesupload value={img3} onChangeImages={this.onChangeSecond.bind(this)} text={'上传国徽面'} className="b_enterpriseform__people_item" count={1} bgImage={peopleLeft}></DImagesupload>
                    }
                </View>
            </View>

        return (
            <View className='b_enterpriseform'>
                <DNavBar title={title}></DNavBar>
                <View className='b_enterpriseform__box'>
                    {
                        success !== 0 && <View className="b_enterpriseform__tips">
                            <Text>{successText}</Text>
                        </View>
                    }
                    <View className='b_enterpriseform__form'>
                        <AtForm>
                            <DAtInpute
                                onChange={this.handleChangeName.bind(this)}
                                value={enterprisefrom.name}
                                title='企业名称'
                                require
                                placeholder='请输入营业执照上的企业名称'
                            ></DAtInpute>
                            <DAtInpute
                                onChange={this.handleChangeAccount.bind(this)}
                                value={enterprisefrom.account}
                                title='社会信用代码'
                                require
                                disabled={edit}
                                maxLength={18}
                                placeholder='请输入企业社会信用代码(区分大小写)'></DAtInpute>
                            <DAtInpute
                                onChange={this.handleChangePeople.bind(this)}
                                value={enterprisefrom.people}
                                title='法人姓名'
                                require
                                placeholder='请输入企业法人姓名'></DAtInpute>
                            <DSelectMap
                                require
                                value={enterprisefrom.region}
                                // className={edit ? 'at-input--disabled' : ''}
                                onChangeHandle={this.onChangeHandle.bind(this)}
                                title='所在区域' placeholder='请选择企业所在城市'></DSelectMap>
                            <DAtInpute
                                require
                                onChange={this.handleChangeItemregion.bind(this)}
                                value={enterprisefrom.itemregion}
                                title='企业地址'
                                placeholder='请输入企业地址（例××市××区××路××号)'></DAtInpute>
                            <DAtInpute
                                require
                                icon='chevron-right' onRightHanlde={this.onHandleType.bind(this)}
                                value={enterprisefrom.type}
                                // className={edit ? 'at-input--disabled' : ''}
                                title='企业性质'
                                placeholder='请选择企业性质'></DAtInpute>
                        </AtForm>
                    </View>
                    <View className='b_enterpriseform__images'>
                        <View className='b_enterpriseform__images_title'>请提供如下资料照片</View>
                        {showimg && itemImagesHtml()}
                        {showimg && itemImagesHtml(1)}
                        {showimg && itemPeople}
                    </View>
                    <View className='b_enterpriseform__footer'>
                        <DAgree type='3' value={status} onHandleChange={this.onHandleChange.bind(this)} text={'《企业认证协议》'}></DAgree>
                        <AtButton className='item_btn' onClick={this.onSubmit.bind(this)}>{this.handleSubmitText.bind(this)()}</AtButton>
                    </View>
                </View>

                <AtActionSheet isOpened={isOpened}>
                    <View className='b_enterpriseform__title'>
                        <View className='b_enterpriseform__title_cancel' onClick={this.onCancelHandle.bind(this)}>取消</View>
                        <View className='b_enterpriseform__title_item'>企业性质</View>
                        <View className='b_enterpriseform__title_submit' onClick={this.onSubmitHandle.bind(this)}>提交</View>
                    </View>
                    <View className='b_enterpriseform__type'>
                        {
                            typeList && typeList.map((item, i) => {
                                return <View onClick={this.onActive.bind(this, i)} className={classNames('b_enterpriseform__type_item', item.status ? 'b_enterpriseform__active' : '')} key={i}>{item.text}</View>
                            })
                        }
                    </View>
                </AtActionSheet>
            </View>
        )
    }
}
